﻿namespace Dcms.BaseClass
{
    using Dcms.ToEmpower;
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Web;
    using System.Configuration;

    public abstract class DcmsTempBaseCreate
    {
        public string AscxPageDir = ConfigurationManager.AppSettings["UserControlsPath"].ToString();
        protected StringBuilder AspxHeadStr = new StringBuilder();
        public string AspxPageDir = ConfigurationManager.AppSettings["AspxPath"].ToString();

        public DcmsTempBaseCreate()
        {
            Dcms.ToEmpower.ToEmpower.ValidateAndRedirect();
        }

        public abstract void CreateFile(string FileContnet, string FileName, string FilePath);
        public string CreateUserControls(string TempRepeartHtml, string CurrLevelIndex, int CurrLevelOrder, string FileName, int ControlsIndex, string LoopRepeaterHtml, string TempFolderName)
        {
            string TempRegStr = "<!--Repeater[^>]*-->((.|\n)*?)<!--Item-->(?<ChildItem>((.|\n)*?))<!--/Item-->((\\s|\n|\r)*?)<!--/Repeater-->";
            string ControlsNameStr = "";
            MatchCollection Nextlevelmymath = new Regex(TempRegStr, RegexOptions.IgnoreCase).Matches(TempRepeartHtml);
            for (int i = 0; i < Nextlevelmymath.Count; i++)
            {
                ControlsNameStr = this.GetUserControlsHtmlSource(Nextlevelmymath[i].Value, this.FormatStrProcess(CurrLevelIndex.ToString(), 0), CurrLevelOrder, FileName, ControlsIndex, LoopRepeaterHtml, TempFolderName);
            }
            return ControlsNameStr;
        }

        public abstract string FormatStrProcess(string CurrIndex, int Step);
        public string GetLoopNesting(string RepeaterHtml, string CurrLevel, int ListId)
        {
            StringBuilder Createhtmlsb = new StringBuilder();
            string TempRegStr = "<!--Repeater[^>]*-->((.|\n)*?)<!--Item-->(?<ChildItem>((.|\n)*?))<!--/Item-->((\\s|\n|\r)*?)<!--/Repeater-->";
            string TempRegConditonStr = "<!--Repeater(?<Conditon>(([^>])*?))-->";
            MatchCollection myConditonmath = new Regex(TempRegConditonStr, RegexOptions.IgnoreCase).Matches(RepeaterHtml);
            MatchCollection myStylemath = new Regex(TempRegStr, RegexOptions.IgnoreCase).Matches(RepeaterHtml);
            for (int i = 0; i < myStylemath.Count; i++)
            {
                Createhtmlsb.Append(string.Concat(new object[] { "<asp:Literal ID=\"Dcms_Label_", CurrLevel, ListId, "FormatSql\"  Visible=\"false\"  EnableViewState=\"false\" runat=\"server\" Text=\"" }));
                Createhtmlsb.Append(HttpUtility.HtmlEncode(this.GetSqlStr(myConditonmath[i].Groups["Conditon"].Value, myStylemath[i].Groups["ChildItem"].Value)));
                Createhtmlsb.Append("\"></asp:Literal>" + Environment.NewLine);
                Createhtmlsb.Append(string.Concat(new object[] { "<asp:Literal ID=\"Dcms_Label_", CurrLevel, ListId, "StyleLevel\"  Visible=\"false\"  EnableViewState=\"false\" runat=\"server\" Text=\"" }));
                Createhtmlsb.Append(HttpUtility.HtmlEncode(this.SplistItem(myStylemath[i].Groups["ChildItem"].Value)));
                Createhtmlsb.Append("\"></asp:Literal>" + Environment.NewLine);
            }
            return Createhtmlsb.ToString();
        }

        public abstract string GetSqlStr(string ConditionStr, string ItemStyleHtml);
        public string GetUserControlsHtmlSource(string RepeaterHtml, string CurrLevel, int ListId, string FileName, int ControlsIndex, string AddHtml, string TempFolderName)
        {
            StringBuilder Createhtmlsb = new StringBuilder();
            string TempRegStr = "<!--Repeater[^>]*-->((.|\n)*?)<!--Item-->(?<ChildItem>((.|\n)*?))<!--/Item-->((\\s|\n|\r)*?)<!--/Repeater-->";
            string TempRegConditonStr = "<!--Repeater(?<Conditon>(([^>])*?))-->";
            MatchCollection myConditonmath = new Regex(TempRegConditonStr, RegexOptions.IgnoreCase).Matches(RepeaterHtml);
            MatchCollection myStylemath = new Regex(TempRegStr, RegexOptions.IgnoreCase).Matches(RepeaterHtml);
            Createhtmlsb.Append("<%@ Control Language=\"C#\" AutoEventWireup=\"true\" CodeFile=\"~/UserControl/SysControl/DcmsModelResolve.cs\" Inherits=\"DcmsModelResolve\" %>" + Environment.NewLine);
            if (AddHtml != "") Createhtmlsb.Append(AddHtml);
            for (int i = 0; i < myStylemath.Count; i++)
            {
                Createhtmlsb.Append(string.Concat(new object[] { "<asp:Literal ID=\"Dcms_Label_", CurrLevel, ListId, "FormatSql\"  Visible=\"false\"  EnableViewState=\"false\" runat=\"server\" Text=\"" }));
                Createhtmlsb.Append(HttpUtility.HtmlEncode(this.GetSqlStr(myConditonmath[i].Groups["Conditon"].Value, myStylemath[i].Groups["ChildItem"].Value)));
                Createhtmlsb.Append("\"></asp:Literal>" + Environment.NewLine);
                Createhtmlsb.Append(string.Concat(new object[] { "<asp:Literal ID=\"Dcms_Label_", CurrLevel, ListId, "StyleLevel\"  Visible=\"false\"  EnableViewState=\"false\" runat=\"server\" Text=\"" }));
                Createhtmlsb.Append(HttpUtility.HtmlEncode(this.SplistItem(myStylemath[i].Groups["ChildItem"].Value)));
                Createhtmlsb.Append("\"></asp:Literal>" + Environment.NewLine);
            }
            Createhtmlsb.Append("<asp:Literal ID=\"LiteralContent\"  EnableViewState=\"false\" runat=\"server\" Text=\"内容\"></asp:Literal>");
            string AscxPageName = "";
            AscxPageName = FileName + "Control" + ControlsIndex.ToString();
            this.CreateFile(Createhtmlsb.ToString(), AscxPageName + ".ascx", this.AscxPageDir + TempFolderName);
            this.AspxHeadStr.Append("<%@ Register Src=\"" + this.AscxPageDir + TempFolderName + "/" + AscxPageName + ".ascx\" TagName=\"" + AscxPageName + "\" TagPrefix=\"Dcms\" %>" + Environment.NewLine);
            return ("<Dcms:" + AscxPageName + " ID=\"" + AscxPageName + "\" runat=\"server\" />");
        }

        private IList<string> RegexGetTempTag(string RegexStr, string Temp)
        {
            IList<string> TempTag = new List<string>();
            MatchCollection matches = new Regex(RegexStr, RegexOptions.IgnoreCase).Matches(Temp);
            if (matches.Count > 0)
            {
                foreach (Match m in matches)
                {
                    TempTag.Add(m.Value);
                }
            }
            return TempTag;
        }

        private IList<int> RegexGetTempTagPosition(string RegexStr, string Temp)
        {
            IList<int> TempTagPosition = new List<int>();
            MatchCollection matches = new Regex(RegexStr, RegexOptions.IgnoreCase).Matches(Temp);
            if (matches.Count > 0)
            {
                foreach (Match m in matches)
                {
                    TempTagPosition.Add(m.Index);
                }
            }
            return TempTagPosition;
        }

        public string ResolveHtml(string HtmlTemp, int ControlsIndex, string FileName, string TempFolderName)
        {
            StringBuilder LoopRepeaterHtml = new StringBuilder();
            string TempRegStr = "<!--Repeater[^>]*-->((.|\n)*?)<!--Item-->(?<ChildItem>((.|\n)*?))<!--/Item-->((\\s|\n|\r)*?)<!--/Repeater-->";
            int StartLabel = HtmlTemp.ToLower().IndexOf("<!--repeater ");
            int EndLabel = HtmlTemp.ToLower().IndexOf("<!--/repeater-->");
            int tempStart = 0;
            int NextStartLabel = 0;
            int NextEndLabel = 0;
            int Flagint = 0;
            int CurrLevelIndex = 1;
            int CurrLevelOrder = 0;
            ArrayList StackArr = new ArrayList();
            string TempRepeartHtml = "";
            while (EndLabel != -1)
            {
                tempStart = StartLabel;
                if (tempStart != -1) NextStartLabel = HtmlTemp.ToLower().IndexOf("<!--repeater ", (int) (tempStart + 13));
                NextEndLabel = HtmlTemp.ToLower().IndexOf("<!--/repeater-->", (int) (EndLabel + 13));
                if (NextStartLabel == -1 && NextEndLabel == -1)
                {
                    if (Flagint == 0)
                    {
                        CurrLevelOrder = 0;
                        TempRepeartHtml = HtmlTemp.Substring(tempStart, EndLabel - tempStart + 0x10);
                        HtmlTemp = this.CreateUserControls(TempRepeartHtml, this.FormatStrProcess(CurrLevelIndex.ToString(), 0), CurrLevelOrder, FileName, ControlsIndex, LoopRepeaterHtml.ToString(), TempFolderName);
                        StartLabel = HtmlTemp.ToLower().IndexOf("<!--repeater ", tempStart);
                        EndLabel = HtmlTemp.ToLower().IndexOf("<!--/repeater-->", tempStart);
                    }
                    else
                    {
                        CurrLevelOrder = 0;
                        Flagint--;
                        CurrLevelIndex = Flagint + 1;
                        tempStart = Convert.ToInt32(StackArr[0]);
                        TempRepeartHtml = HtmlTemp.Substring(tempStart, EndLabel - tempStart + 0x10);
                        HtmlTemp = this.CreateUserControls(TempRepeartHtml, this.FormatStrProcess(CurrLevelIndex.ToString(), 0), CurrLevelOrder, FileName, ControlsIndex, LoopRepeaterHtml.ToString(), TempFolderName);
                        StartLabel = HtmlTemp.ToLower().IndexOf("<!--repeater ", tempStart);
                        EndLabel = HtmlTemp.ToLower().IndexOf("<!--/repeater-->", tempStart);
                        StackArr.Remove(StackArr[Flagint]);
                    }
                }
                else if (NextStartLabel < EndLabel && NextStartLabel != -1)
                {
                    StackArr.Add(tempStart);
                    Flagint++;
                    CurrLevelOrder = 0;
                    CurrLevelIndex++;
                    StartLabel = HtmlTemp.ToLower().IndexOf("<!--repeater ", (int) (tempStart + 13));
                    EndLabel = HtmlTemp.ToLower().IndexOf("<!--/repeater-->", (int) (tempStart + 13));
                }
                else
                {
                    string ControlsNameStr;
                    Regex ReplaceReg;
                    MatchCollection Nextlevelmymath;
                    int i;
                    if (StartLabel < EndLabel && StartLabel != -1)
                    {
                        CurrLevelIndex = Flagint + 1;
                        ControlsNameStr = "";
                        TempRepeartHtml = HtmlTemp.Substring(tempStart, EndLabel - tempStart + 0x10);
                        ReplaceReg = new Regex(TempRegStr, RegexOptions.IgnoreCase);
                        Nextlevelmymath = ReplaceReg.Matches(TempRepeartHtml);
                        i = 0;
                        while (i < Nextlevelmymath.Count)
                        {
                            ControlsNameStr = this.GetLoopNesting(Nextlevelmymath[i].Value, this.FormatStrProcess(CurrLevelIndex.ToString(), 0), CurrLevelOrder);
                            LoopRepeaterHtml.Append(ControlsNameStr);
                            i++;
                        }
                        HtmlTemp = ReplaceReg.Replace(HtmlTemp, string.Concat(new object[] { "{Dcms_Label_", this.FormatStrProcess(CurrLevelIndex.ToString(), 0), CurrLevelOrder, "}" }), 1, tempStart);
                        StartLabel = HtmlTemp.ToLower().IndexOf("<!--repeater ", tempStart);
                        EndLabel = HtmlTemp.ToLower().IndexOf("<!--/repeater-->", tempStart);
                        CurrLevelOrder++;
                    }
                    else
                    {
                        Flagint--;
                        CurrLevelOrder = 0;
                        ControlsNameStr = "";
                        tempStart = Convert.ToInt32(StackArr[Flagint]);
                        CurrLevelIndex = Flagint + 1;
                        TempRepeartHtml = HtmlTemp.Substring(tempStart, EndLabel - tempStart + 0x10);
                        ReplaceReg = new Regex(TempRegStr, RegexOptions.IgnoreCase);
                        Nextlevelmymath = ReplaceReg.Matches(TempRepeartHtml);
                        for (i = 0; i < Nextlevelmymath.Count; i++)
                        {
                            ControlsNameStr = this.GetLoopNesting(Nextlevelmymath[i].Value, this.FormatStrProcess(CurrLevelIndex.ToString(), 0), CurrLevelOrder);
                            LoopRepeaterHtml.Append(ControlsNameStr);
                        }
                        HtmlTemp = ReplaceReg.Replace(HtmlTemp, string.Concat(new object[] { "{Dcms_Label_", this.FormatStrProcess(CurrLevelIndex.ToString(), 0), CurrLevelOrder, "}" }), 1, tempStart);
                        StartLabel = HtmlTemp.ToLower().IndexOf("<!--repeater ", tempStart);
                        EndLabel = HtmlTemp.ToLower().IndexOf("<!--/repeater-->", tempStart);
                        StackArr.Remove(StackArr[Flagint]);
                        CurrLevelOrder++;
                    }
                }
            }
            return HtmlTemp;
        }

        public string SplistItem(string Html)
        {
            Html = Regex.Replace(Html, "\n", "");
            Html = Regex.Replace(Html, "\r", "");
            Html = Regex.Replace(Html, "\t", "");
            Html = Regex.Replace(Html, "  ", "");
            Html = Regex.Replace(Html, "<!--/Item-->((.|\n)*?)<!--Item-->", "$dcmsItem$");
            return Html;
        }

        public string SplitRepeaterBlock(string HtmlTemp, string TempFolderName, string FileName)
        {
            string RegexStr = "<!--[^>]*Repeater[^>]*-->";
            IList<string> TempTag = new List<string>();
            TempTag = this.RegexGetTempTag(RegexStr, HtmlTemp);
            IList<int> TempTagPosition = new List<int>();
            TempTagPosition = this.RegexGetTempTagPosition(RegexStr, HtmlTemp);
            string TempCotrolsLinkStr = "";
            string CreateControlHtmlTemp = "";
            string OldHtmlTemp = "";
            int RegexNmu = 0;
            int ControlsIndex = 0;
            int StarIndex = 0;
            int EndIndex = 0;
            OldHtmlTemp = HtmlTemp;
            for (int i = 0; i < TempTag.Count; i++)
            {
                if (new Regex("^<!--Repeater[^>]*-->$").IsMatch(TempTag[i].ToString()))
                {
                    RegexNmu++;
                    if (RegexNmu == 1) StarIndex = TempTagPosition[i];
                }
                else
                {
                    RegexNmu--;
                    EndIndex = TempTagPosition[i] + 0x10;
                }
                if (RegexNmu == 0)
                {
                    ControlsIndex++;
                    CreateControlHtmlTemp = OldHtmlTemp.Substring(StarIndex, EndIndex - StarIndex);
                    TempCotrolsLinkStr = this.ResolveHtml(CreateControlHtmlTemp, ControlsIndex, FileName, TempFolderName);
                    HtmlTemp = HtmlTemp.Replace(CreateControlHtmlTemp, TempCotrolsLinkStr);
                }
            }
            return HtmlTemp;
        }
    }
}

